<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".__("Messaging");
$page_title=__("Messaging");

if(!$pv["task"]["Messaging"]){
 $errmsg="<h2>$page_title</h2>".format_err(__("You do not have the privilege to manage messaging."));
            
 print format_admin_page($errmsg, $this_title);
 exit();
}

$item_per_page=$vars['admin_item_per_page'];
$td_width=150;

//tab
$css="<link rel='stylesheet' type='text/css' href='".CSS_URL."/tab/tab".(USER_BROWSER=='msie'? "-ie" : "").".css' />\n";
$tab=
"<ul class='tabs-nav' id='_tab'>
  <li class='tabs-".($_GET['action']=='inbox' || !$_GET['action']? "" : "un")."selected' rel='inbox'><a href='".$vars['file']['admin']['support']."?action=inbox'><span>".__("Inbox")."</span></a></li>
  <li class='tabs-".($_GET['action']=='new'? "" : "un")."selected' rel='new'><a href='".$vars['file']['admin']['support']."?action=new'><span>".__("Compose")."</span></a></li>
  <li class='tabs-".($_GET['action']=='outbox'? "" : "un")."selected' rel='outbox'><a href='".$vars['file']['admin']['support']."?action=outbox'><span>".__("Outbox")."</span></a></li>
</ul>
<div class='tabs-panel' style='width:100%;'><%tab_content%></div>";

//#####AJAX CALL#####
if($_GET["aj"] && $_GET["check_uid"]){
	$ajresult = ajax_check_user($post_d['uid']);
	if($ajresult['status'] == 3){
		$ajmsg = "The Member ID '$post_s[uid]' could not be found.";
	}elseif($ajresult['status'] == 2){
		$ajmsg = "The Member ID '$post_s[uid]' could not be found.";
	}elseif($ajresult['status'] == 1){
		$ajmsg = "Member ID '$post_s[uid]', name: {$ajresult['user_detail']['name']}";
	}
	$status = $ajresult['status'];

	print format_xml(array('status'=>$status, 'msg'=>$ajmsg));
	exit;
}
//#####END AJAX CALL#####

if($_GET['action']=="new"){
 //#####POST#####
 if($_POST['__req']){
  $errmsg=verify_form_data("messaging", $post_s);
  if(!$errmsg){
   if(!$recipient=get_user_detail_by_id($post_s['to_uid'])){
    $errmsg=replace_tag(__("The member ID '<%uid%>' could not be found."), array("<%uid%>"=>$post_h['to_uid']))."<br />\n";
   }
  }
  if(!$errmsg){
   $datetime=ndate("");
   $sql="insert into $db->messaging (from_type, from_uid, from_deleted, to_type, to_uid, to_read, to_deleted, subject, message, cdate) values ('a', '$aid', 'n', 'u', '$post_d[to_uid]', 'n', 'n', '$post_d[_subject]', '$post_d[_message]', '$datetime')";
   if(mysql_query($sql)){
    $msg.=__("Your message has been successfully sent.")."<br />\n";
    send_recipient($recipient['name'], $recipient['email']);
   }else{
    $errmsg.=__("There is some error and your message could not be sent. Please try again later.")."<br />\n";
   }
  }

  $msg=$msg? format_msg($msg) : "";
  $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
 }
 //#####END POST#####

 $form_fields=array("to_uid"=>"","_subject"=>"","_message"=>"");
 foreach($form_fields as $field => $default){
  $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
  $dis[$field]=!$post_s["__req"]? $default : $post_h[$field];
 }

 $messaging=$msg.$errmsg."
 <form name='new_form' method='post' action='$this_file?action=new'>
 <input type='hidden' name='__req' value='1' />
 <input type='hidden' name='support' value='new' />
 <input type='hidden' name='action' value='new' />
 <table class='amt_table'>
  <tr>
   <td width='$td_width'>".__("Member ID").__(":").__("*")."</td>
   <td><input type='text' name='to_uid' value=\"$dis[to_uid]\" $inputbox_style />
       <input type='button' id='check_uid_btn' value=\"".__("Load Member")."\" /> <div id='member_detail'></div></td>
  </tr>   
  <tr>
   <td width='$td_width'>".__("Subject").__(":").__("*")."</td>
   <td><input type='text' name='_subject' value=\"$dis[_subject]\" $inputbox_style /></td>
  </tr>                                                             
  <tr>
   <td>".__("Message").__(":").__("*")."</td>
   <td><textarea name='_message' $inputbox_style rows='15'>$dis[_message]</textarea></td>
  </tr>
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='submit' name='submit_btn' value=\"".__("Send")."\" />
  </td>
 </table>
 </form>";
//#################INBOX
}elseif($_GET['action']=="inbox" || !$_GET['action']){
 //back button
 $url_referer=$_SERVER["HTTP_REFERER"];
 if($post_s["back_url"]){
  $back_url=$post_s["back_url"];
 }elseif($url_referer && !strstr($url_referer, $this_file)){
  $back_url=$url_referer;
 }else{
  $back_url=$vars['file']['member']['support']."?action=inbox";
 }

 //#####VIEW A MESSAGE#####
 if($_GET['view']){
  if(!$_GET['mid'] || !is_numeric($_GET['mid']) || $_GET['mid'] <= 0){
   $errmsg=__("Invalid message.")."<br />\n";
  }elseif(!@mysql_num_rows($r=mysql_query("select * from $db->messaging where id='$get_d[mid]' and to_type='a'"))){
   $errmsg=__("Invalid message.")."<br />\n";
  }

  if($errmsg){
   $messaging=format_err($errmsg);
  }else{
   $message=mysql_fetch_assoc($r);

   //update message to read, if not already
   if($message['to_read']!='y'){
    if(!mysql_query($sql="update $db->messaging set to_read='y' where id='$message[id]' limit 1")){
     $critical_error.="Error updating the message ID: $message[id] to 'read' status.<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
    }
   }

   //#####REPLY POST#####
   if($_POST['__req']){
    $errmsg=verify_form_data("messaging", $post_s);

    if(!$errmsg){
     $datetime=ndate();
     $subject=(substr($message['subject'], 0, 3)!='RE:'? 'RE: ' : '').AddSlashes($message['subject']);
     $sql="insert into $db->messaging (from_type, from_uid, from_deleted, to_type, to_uid, to_read, to_deleted, subject, message, cdate) values ('a', '$aid', 'n', '".mysql_real_escape_string($message['from_type'])."', '".mysql_real_escape_string($message['from_uid'])."', 'n', 'n', '$subject', '$post_d[_message]', '$datetime')";
     if(mysql_query($sql)){
      $msg=__("Your message has been successfully sent.")."<br />\n";
      $sender=get_user_detail_by_id($message['from_uid']);
      send_recipient($sender['name'], $sender['email']);
     }else{
      $errmsg=__("There is some error and your message could not be sent. Please try again later.")."<br />\n";
     }
    }

    $msg=$msg? format_msg($msg) : "";
    $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
   }
   //#####END REPLY POST#####

   $form_fields=array("_message"=>"");
   foreach($form_fields as $field => $default){
    $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
    $dis[$field]=!$post_s["__req"]? $default : $post_h[$field];
   }

   if($message['from_type']=='u'){
    $sender=get_user_detail_by_id($message['from_uid']);
    $sender="$sender[name] (UID #$sender[id])";
   }else{
    $sender=__("Management");
   }
   $inbox=$errmsg.$msg.
   "<form name='reply_form' method='post' action='$this_file?action=inbox&view=1&mid=$message[id]'>
   <input type='hidden' name='__req' value='1' />
   <input type='hidden' name='back_url' value=\"$back_url\" />
   <table class='pbt_table'>
    <tr>
     <td width='$td_width'>".__("Subject").__(":")."</td>
     <td>$message[subject]</td>
    </tr>
    <tr>
     <td width='$td_width'>".__("Sender").__(":")."</td>
     <td>$sender</td>
    </tr>
    <tr>
     <td width='$td_width'>".__("Received").__(":")."</td>
     <td>".date($vars['date_format'], strtotime($message['cdate']))."</td>
    </tr>
    <tr>
     <td width='$td_width'>".__("Message").__(":")."</td>
     <td>".nl2br($message['message'])."</td>
    </tr>
    <tr>
     <td width='$td_width'>".__("Add Reply").__(":")."</td>
     <td><textarea name='_message' $inputbox_style rows='15'>$dis[_message]</textarea></td>
    </tr>
    <tr>
     <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
      <input type='button' value=\"".__("Back")."\" onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
      <input type='submit' name='submit_btn' value=\"".__("Send")."\" />
     </td>
    </tr>
   </table>
   </form>";
   $messaging=$inbox;
  }
 }
 //#####END VIEW A MESSAGE#####

 //#####DELETE MESSAGE POST#####
 if($_POST['__req'] && $_POST['delete']){
  foreach($post_s as $f=>$v){
   if($v && preg_match('/^mid[0-9]+$/', $f)){
    $mid.=($mid? "," : "").preg_replace('/^mid/', '', $f);
    $dis[$f]=$v;
   }
  }

  if(!$mid){
   $errmsg.=__("Please select a message to delete.")."<br />\n";
  }else{
   $sql="update $db->messaging set to_deleted='y' where id in ($mid)";
   if(mysql_query($sql)){
    $msg=__("The selected message(s) has been successfully deleted.")."<br />\n";
   }else{
    $errmsg.=__("There is some error and your message could not be deleted. Please try again later.")."<br />\n";
   }
  }

  $msg=$msg? format_msg($msg) : "";
  $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
 }
 //#####END DELETE MESSAGE POST#####

 //#####LIST ALL MESSAGES#####
 if(!$_GET['view']){
  $count_sql="select count(*) from $db->messaging where to_type='a' and to_deleted='n'";
  $record_sql="select * from $db->messaging where to_type='a' and to_deleted='n' order by cdate desc limit <%limit_start%>, <%limit%>";

  $cur_page=$_GET["nav"];
  $total_record=@mysql_result(mysql_query($count_sql), 0);
  $total_page=ceil($total_record/$item_per_page);
  $page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
  $limit_start=($page-1)*$item_per_page;
  $nav_link=format_page_admin($page, $total_page, $this_file);
  $this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
  $total_unread=0;
  for($i=0;$i<$this_page_total;$i++){
   $message=mysql_fetch_assoc($r);
   if($message['from_type']=='u' && !$users[$message["from_uid"]]){
    $users[$message["from_uid"]]=get_user_detail_by_id($message['from_uid']);
   }
   if($message['to_read']=='n'){
    $total_unread++;
   }
   $message_row.="
   <div class='inbox_row".($message['to_read']=='n'? " inbox_unread" : "")."'>
    <div class='inbox_chk'><input type='checkbox' name='mid$message[id]'".($dis['mid'.$message['id']]? " checked='checked'" : "")." /></div>
    <div class='inbox_sender'><a href='$this_file?action=inbox&view=1&mid=$message[id]'>".($message['from_type']=='u'? $users[$message['from_uid']]['name'] : __("Management"))."</a></div>
    <div class='inbox_subject'><a href='$this_file?action=inbox&view=1&mid=$message[id]'>$message[subject]</a></div>
    <div class='inbox_date'><a href='$this_file?action=inbox&view=1&mid=$message[id]'>".(strtotime($message['cdate'])>=mktime(0,0,0,ndate('n'),ndate('j'),ndate('Y'))? date($vars['inbox_date_format_today'], strtotime($message['cdate'])) : date($vars['inbox_date_format'], strtotime($message['cdate'])))."</a></div><div class='clear'></div>
   </div>";
  }
  $message_list=$msg.$errmsg.
  replace_tag(__("<%x%> <%message%>, <%y%> unread."), array("<%x%>"=>strval($total_record), "<%message%>"=>$total_record>1? __("messages") : __("message"), "<%y%>"=>strval($total_unread)))."
  $nav_link
  <form name='delete_inbox_form' method='post' action='$this_file?action=inbox'>
  <input type='hidden' name='__req' value='1' />
  <input type='hidden' name='delete' value='1' />
  <input type='hidden' name='back_url' value=\"$back_url\" />
  <div class='inbox_row inbox_header'>
   <div class='inbox_chk'></div>
   <div class='inbox_sender'>".__("Sender")."</div>
   <div class='inbox_subject'>".__("Subject")."</div>
   <div class='inbox_date'>".__("Received")."</div><div class='clear'></div>
  </div>
  $message_row
  $nav_link
  <p class='center'><input type='submit' name='submit_btn' value=\"".__("Delete")."\" /></p>
  </form>";

  $messaging=$message_list;
 }
 //#####END LIST ALL MESSAGES#####
//#################OUTBOX
}elseif($_GET['action']=="outbox"){
 //back button
 $url_referer=$_SERVER["HTTP_REFERER"];
 if($post_s["back_url"]){
  $back_url=$post_s["back_url"];
 }elseif($url_referer && !strstr($url_referer, $this_file)){
  $back_url=$url_referer;
 }else{
  $back_url=$vars['file']['member']['support']."?action=outbox";
 }

 //#####VIEW A MESSAGE#####
 if($_GET['view']){
  if(!$_GET['mid'] || !is_numeric($_GET['mid']) || $_GET['mid'] <= 0){
   $errmsg=__("Invalid message.")."<br />\n";
  }elseif(!@mysql_num_rows($r=mysql_query("select * from $db->messaging where id='$get_d[mid]' and from_type='a'"))){
   $errmsg=__("Invalid message.")."<br />\n";
  }

  if($errmsg){
   $messaging=format_err($errmsg);
  }else{
   $message=mysql_fetch_assoc($r);

   if($message['to_type']=='u'){
    $recipient=get_user_detail_by_id($message['to_uid']);
    $recipient="$recipient[name] (UID #$recipient[id])";
   }else{
    $recipient=__("Management");
   }
   $outbox=$errmsg.$msg.
   "<input type='hidden' name='back_url' value=\"$back_url\" />
   <table class='pbt_table'>
    <tr>
     <td width='$td_width'>".__("Subject").__(":")."</td>
     <td>$message[subject]</td>
    </tr>
    <tr>
     <td width='$td_width'>".__("Recipient").__(":")."</td>
     <td>$recipient</td>
    </tr>
    <tr>
     <td width='$td_width'>".__("Sent").__(":")."</td>
     <td>".date($vars['date_format'], strtotime($message['cdate']))."</td>
    </tr>
    <tr>
     <td width='$td_width'>".__("Message").__(":")."</td>
     <td>".nl2br($message['message'])."</td>
    </tr>
    <tr>
     <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
      <input type='button' value=\"".__("Back")."\" onclick=\"location='$back_url';\">
     </td>
    </tr>
   </table>";
   $messaging=$outbox;
  }
 }
 //#####END VIEW A MESSAGE#####

 //#####DELETE MESSAGE POST#####
 if($_POST['__req'] && $_POST['delete']){
  foreach($post_s as $f=>$v){
   if($v && preg_match('/^mid[0-9]+$/', $f)){
    $mid.=($mid? "," : "").preg_replace('/^mid/', '', $f);
    $dis[$f]=$v;
   }
  }

  if(!$mid){
   $errmsg.=__("Please select a message to delete.")."<br />\n";
  }else{
   $sql="update $db->messaging set from_deleted='y' where id in ($mid)";
   if(mysql_query($sql)){
    $msg=__("The selected message(s) has been successfully deleted.")."<br />\n";
   }else{
    $errmsg.=__("There is some error and your message could not be deleted. Please try again later.")."<br />\n";
   }
  }

  $msg=$msg? format_msg($msg) : "";
  $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
 }
 //#####END DELETE MESSAGE POST#####

 if(!$_GET['view']){
  $count_sql="select count(*) from $db->messaging where from_type='a' and from_deleted='n'";
  $record_sql="select * from $db->messaging where from_type='a' and from_deleted='n' order by cdate desc limit <%limit_start%>, <%limit%>";

  $cur_page=$_GET["nav"];
  $total_record=@mysql_result(mysql_query($count_sql), 0);
  $total_page=ceil($total_record/$item_per_page);
  $page=($cur_page? ($cur_page>$total_page? $total_page : ($cur_page<1? 1 : $cur_page)) : 1);
  $limit_start=($page-1)*$item_per_page;
  $nav_link=format_page_admin($page, $total_page, $this_file);
  $this_page_total=@mysql_num_rows($r=mysql_query(str_replace("<%limit_start%>", $limit_start, str_replace("<%limit%>", $item_per_page, $record_sql))));
  $total_unread=0;
  for($i=0;$i<$this_page_total;$i++){
   $message=mysql_fetch_assoc($r);
   if($message['to_type']=='u' && !$users[$message["to_uid"]]){
    $users[$message["to_uid"]]=get_user_detail_by_id($message['to_uid']);
   }
   $message_row.="
   <div class='outbox_row'>
    <div class='outbox_chk'><input type='checkbox' name='mid$message[id]'".($dis['mid'.$message['id']]? " checked='checked'" : "")." /></div>
    <div class='outbox_recipient'><a href='$this_file?action=outbox&view=1&mid=$message[id]'>".($message['to_type']=='u'? $users[$message['to_uid']]['name'] : __("Management"))."</a></div>
    <div class='outbox_subject'><a href='$this_file?action=outbox&view=1&mid=$message[id]'>$message[subject]</a></div>
    <div class='outbox_date'><a href='$this_file?action=outbox&view=1&mid=$message[id]'>".(strtotime($message['cdate'])>=mktime(0,0,0,ndate('n'),ndate('j'),ndate('Y'))? date($vars['inbox_date_format_today'], strtotime($message['cdate'])) : date($vars['inbox_date_format'], strtotime($message['cdate'])))."</a></div><div class='clear'></div>
   </div>";
  }
  $message_list=$msg.$errmsg.
  replace_tag(__("<%x%> <%message%>."), array("<%x%>"=>strval($total_record), "<%message%>"=>$total_record>1? __("messages") : __("message")))."
  $nav_link
  <form name='delete_outbox_form' method='post' action='$this_file?action=outbox'>
  <input type='hidden' name='__req' value='1' />
  <input type='hidden' name='delete' value='1' />
  <input type='hidden' name='back_url' value=\"$back_url\" />
  <div class='outbox_row outbox_header'>
   <div class='outbox_chk'></div>
   <div class='outbox_recipient'>".__("Recipient")."</div>
   <div class='outbox_subject'>".__("Subject")."</div>
   <div class='outbox_date'>".__("Sent")."</div><div class='clear'></div>
  </div>
  $message_row
  $nav_link
  <p class='center'><input type='submit' name='submit_btn' value=\"".__("Delete")."\" /></p>
  </form>";

  $messaging=$message_list;
 }
}
//end process support

//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('form[@name=delete_inbox_form],form[@name=delete_outbox_form]').submit(function(){
  if(!confirm('".AddSlashes("Delete the selected message(s). Are you sure?")."')){
   return false;
  }
 });

 j('input[@name=to_uid]').click(function(){
  j('input[@name=to_type]:last').attr('checked','checked');
 });

 j('input#check_uid_btn').click(function(){
  j('div#member_detail').html('').removeClass('red');
  if(j('input[@name=to_uid]').val()==''){
   j('div#member_detail').html('".AddSlashes(__("Please provide a Member ID!"))."').addClass('red');
  }else{
   j(this).attr('disabled','disabled');
   j.ajax({
    url: '$this_file?aj=1&check_uid=1',
    data: {'uid': j('input[@name=to_uid]').val()},
    type: 'post',
    dataType: 'xml',
    error: function(){
     j('div#member_detail').html('".AddSlashes(__("Error checking..."))."').addClass('red');
    },
    success: function(data){
     var mesg='';
     if(j('loggedout', data).text()=='loggedout'){
      mesg='".AddSlashes(__("You have been logged out."))."';
     }else{
      j(data).find('msg').each(function(){
       mesg+=j(this).text()+' ';
      });
     }
     var status=j(data).find('status').text();
     j('div#member_detail').html(mesg).addClass(status==1? 'bold' : 'red');
    },
    complete: function(){
     j('input#check_uid_btn').attr('disabled','');
    }
   });
  }
 });
});
</script>";

$tab_content=$messaging;
$content="<h2>$page_title</h2>".str_replace("<%tab_content%>", $tab_content, $tab);
print format_admin_page($content, $this_title, $css.$jvscript);

function send_recipient($to_name, $to_email){
 global $vars;

 $recipient=$to_name;
 $u_sub="$vars[title] - You Have a New Message";
 $u_msg="
 <p>Dear $recipient,</p>
 <p>You have a new message in your $vars[title] account. Please login to $vars[title] to check your message.</p>";
 email_user($to_email, $u_sub, $u_msg);
}
?>